package com.base.system.config.security;

import cn.hutool.core.util.StrUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Optional;

public final class UserKit {
    private UserKit(){};

    public static Optional<AuthUser> getCurrentUser(){
        SecurityContext context = SecurityContextHolder.getContext();
        return Optional.ofNullable(context.getAuthentication()).map((authentication)->{
            if(authentication.getPrincipal() instanceof UserDetails){
                return (AuthUser)authentication.getPrincipal();
            }else{
                return null;
            }
        });
    }

    public static AuthUser getUserByToken(String token){
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();

        if(StrUtil.equals((String)authentication.getCredentials(),token)){
            return ((AuthUser) authentication.getPrincipal());
        }else {
            return null;
        }
    }

}
